﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

using System;
using System.IO;

using zijian666.Core;
using zijian666.WebApi.SwaggerOptions;

namespace zijian666.WebApi
{
    /// <summary>
    /// WebApi选项组
    /// </summary>
    public partial class WebApiOptions
    {
        /// <summary>
        /// 启用文档支持
        /// </summary>
        /// <param name="title">文档标题</param>
        /// <param name="version">文档版本</param>
        public void EnableSwaggerGen(string? title = null, string? version = "v1")
        {
            if (title is null)
            {
                title = AppDomain.CurrentDomain.FriendlyName;
            }

            if (version is null)
            {
                version = "v1";
            }

            _services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = title, Version = version });
                options.OperationFilter<AuthorizeAttributeFilter>();
                options.DocumentFilter<SupportMultipleMethodsFilter>();

                foreach (var xml in Directory.EnumerateFiles(AppContext.BaseDirectory, "*.xml", SearchOption.AllDirectories))
                {
                    try
                    {
                        options.IncludeXmlComments(xml, true);
                    }
                    catch (Exception ex)
                    {
                        ErrorReporter.Report(ex, this, xml);
                    }
                }

                foreach (var xml in Directory.EnumerateFiles(".", "*.xml", SearchOption.TopDirectoryOnly))
                {
                    try
                    {
                        options.IncludeXmlComments(xml, true);
                    }
                    catch (Exception ex)
                    {
                        ErrorReporter.Report(ex, this, xml);
                    }
                }
            });
            _services.ConfigureSwaggerGen(options => options.OperationFilter<SwaggerFormatResultFilter>());
            AddConfigureHandler("swagger", app => {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.DocumentTitle = $"{title} ApiDoc {version}";
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", $"{title} {version}");
                });
            });
        }
    }
}
